<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 模块创建助手暂时仅可用于admin模块创建
//+---------------------------------------------------------------------------------------------------------------------


namespace helper\assistant;


use think\Exception;
use think\helper\Str;

class Create
{
	CONST _BASECONFIG = [
		'admin' => [
			'controller' => '\\app\\admin\\controller\\Admin',
			'service' => '\\app\\admin\\service\\AdminService',
			'model' => '\\app\\admin\\model\\AdminModel',
			'validate' => '\\app\\admin\\validate\\AdminValidate'
		]
	];

	/**
	 * 模块名
	 * @var string
	 */
	protected $module;

	/**
	 * 控制器等的名字
	 * @var string
	 */
	protected $name;

	/**
	 * 配置
	 * @var string[]
	 */
	protected $config;

	public function __construct($module,$name){
		$this->module = $module;
		$this->name = $name;
		$this->config = self::_BASECONFIG[$this->module];
	}

	/**
	 * 创建控制器
	 * @return $this
	 * @throws Exception
	 */
	public function controller(){
		$baseController = ltrim($this->config[__FUNCTION__],'\\');
		$baseControllerInfo = explode('\\',$baseController);
		$baseControllerName = array_pop($baseControllerInfo);
		$namespace = join('\\',$baseControllerInfo);
		$content = '<?php
namespace '.$namespace.';

class '.ucfirst($this->name).' extends '.$baseControllerName.'
{

	protected $noNeedLogin = [\'*\'];
	
	public function index()
	{
		if ( $this->request->isAjax() ){
		if($this->request->has(\'keyword\',\'post\')){
				$keyword = $this->request->post(\'keyword\');
				$where = [];
			}else{
				$where = [];
			}
			return $this->service->getTableList($where);
		}
		return $this->fetch();
	}
	
	public function create()
	{
		if ( $this->request->isPost() ){
			return $this->service->create();
		}
		return $this->fetch();
	}
	
	public function update($id=null)
	{
		if ( $this->request->isPost() ){
			$this->service->update();
		}
		
		$info = $this->service->getModel()->find($id);
		$this->assign(\'info\', $info);
		return $this->fetch();
	}
	
	public function delete(){
		return $this->service->delete();
	}
	
}
';
		try{
			return $this->build($content,__FUNCTION__);
		}catch (\Exception $e){
			throw new Exception('异常,创建控制器失败');
		}
	}

	/**
	 * 创建模型
	 * @return $this
	 * @throws Exception
	 */
	public function model(){
		$baseModel = ltrim($this->config[__FUNCTION__],'\\');
		$baseModelInfo = explode('\\',$baseModel);
		$baseModelName = array_pop($baseModelInfo);
		$namespace = join('\\',$baseModelInfo);

		$content = '<?php
namespace '.$namespace.';

class '.ucfirst($this->name).' extends '.$baseModelName.'
{
	protected $name = \'表名\';
	
	/**
	 * 新增、更新需要操作的字段
	 */
	protected $submitField = [
		\'字段名\' => \'字段类型\',//暂时只支持int、string、json、serialize、float、decimal
	];

}

';
		try{
			return $this->build($content,__FUNCTION__);
		}catch (\Exception $e){
			throw new Exception('异常,创建控制器失败');
		}
	}

	/**
	 * 创建验证器
	 * @return $this
	 * @throws Exception
	 */
	public function validate(){
		$baseValidate = ltrim($this->config[__FUNCTION__],'\\');
		$baseValidateInfo = explode('\\',$baseValidate);
		$baseValidateName = array_pop($baseValidateInfo);
		$namespace = join('\\',$baseValidateInfo);

		$content = '<?php
namespace '.$namespace.';

class '.ucfirst($this->name).'Validate extends '.$baseValidateName.'
{
	protected $rule = [];
	
	protected $message = [];
	
	protected $scene = [];
}

';
		if(file_put_contents(app()->getAppPath().$this->module.'/' . __FUNCTION__ . '/'.ucfirst($this->name).'Validate.php',$content)){
			return $this;
		}
		throw new Exception('异常,创建控制器失败');
	}

	/**
	 * 创建业务层
	 * @return $this
	 * @throws Exception
	 */
	public function service(){
		$baseService = ltrim($this->config[__FUNCTION__],'\\');
		$baseServiceInfo = explode('\\',$baseService);
		$baseServiceName = array_pop($baseServiceInfo);
		$namespace = join('\\',$baseServiceInfo);

		$model = 'app\\' . $this->module . '\\model\\'.ucfirst($this->name);
		$validate = 'app\\'. $this->module.'\\validate\\'.ucfirst($this->name).'Validate';

		$content = '<?php
namespace '.$namespace.';

use '.$model.' as Model;
use '.$validate.' as Validate;

class '.ucfirst($this->name) .' extends AdminService 
{

	  protected function init(){
        $this->model = new Model();
        $this->validate = new Validate();
    }

}

';

		try{
			return $this->build($content,__FUNCTION__);
		}catch (\Exception $e){
			throw new Exception('异常,创建控制器失败');
		}
	}

	/**
	 * 创建视图
	 */
	public function view(){
		$dirname = app()->getAppPath().$this->module.'/'.__FUNCTION__.'/'.Str::snake($this->name);
		mkdir($dirname,0777,true);

		$index = '{extend name="common/block" /}
{block name="content"}
<div class="layui-btn-container " style="display: inline-block;">
    <button id="btnDeleteChecked" class="layui-btn layui-btn-sm layui-btn-danger">
        <i class="layui-icon">&#xe640;</i>批量删除
    </button>
    <button class="layui-btn layui-btn-sm j-open layui-btn-normal"
            j-href=\'{:url("create")}\'
            j-title="新增"
            j-type="2"
            j-config=\'{"area":["80%","80%"],"anim":2}\'
    >
        <i class="layui-icon">&#xe654;</i>新增
    </button>

</div>
<div class="j-right" style="display: inline-block;line-height:40px">
    <input class="layui-input" id="edtSearch" value="" placeholder="输入搜索条件"
           style="display: inline-block;width: 140px;height: 30px;line-height: 30px;padding: 0 5px;margin-right: 5px;"/>
    <div class="layui-btn-container" style="display: inline-block;">
        <button id="btnSearch" class="layui-btn layui-btn-sm layui-btn-primary">
            <i class="layui-icon">&#xe615;</i>搜索
        </button>
        <button id="btnClearSearch" class="layui-btn layui-btn-sm layui-btn-primary">
            <i class="layui-icon">&#x1006;</i>清除搜索
        </button>
    </div>
</div>

<script type="text/html" id="opera">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<table id="table" lay-filter="' . $this->name . '"></table>
{/block}

{block name="script"}
<script>
    layui.use([\'table\', \'layer\', \'jquery\'], function () {
        var table = layui.table
            , layer = layui.layer
            , $ = layui.jquery;

        table.render({
            elem: \'#table\',
            url: \'{:url("index")}\',
            page: true,
            height: \'full-200\',
            toolbar: \'#opera\',
            method:\'post\',
            cols: [[ //表头
                {type:\'checkbox\'}
            ]],
        })
        
         table.on(\'tool(' . $this->name . ')\', function(obj){
            var data = obj.data;
            if(obj.event === \'del\'){
                layer.confirm(\'确定执行删除操作\', function(index){
                    layer.close(index);
                    $.get(\'delete\', {id:data.id},function(r){
                        if(r.code == 1){
                            showpopup(r.msg);
                            obj.del();
                        }else{
                            showpopup(r.msg);
                        }
                    },\'json\')
                });
            } else if(obj.event === \'edit\'){
                layer.open({
                    type:2,
                    content:\'update?id=\'+data.id,
                    shadeClose:true,
                    area:[\'80%\',\'80%\'],
                })
            }
        });
})
</script>
{/block}
';
		file_put_contents($dirname.'/index.html', $index);


		$create = '{extend name="common/pop" /}
{block name="content"}

<div class="layui-form" style="margin-top:15px;width:90%;">

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter=\'create\'>立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</div>
{/block}

{block name="script"}
<script>
    layui.use([\'layer\',\'jquery\',\'form\'],function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.jquery;

        form.render();


        form.on(\'submit(create)\',function(data){
            $.post(\'{:url("create")}\',data.field,function(r){
                if(r.code == 1){
                    layer.msg(r.msg);
                    close(1500,true);
                }else{
                    layer.msg(r.msg);
                }
            },\'json\')
        });
    })
</script>
{/block}

';
		file_put_contents($dirname.'/create.html',$create);
		$update = str_replace('create','update',$create);
		$update = str_replace('update"','update",["id"=>$info["id"]]',$create);
		file_put_contents($dirname.'/update.html',$update);
	}

	protected function build($content,$type){
		if(file_put_contents(app()->getAppPath().$this->module.'/' . $type . '/'.ucfirst($this->name).'.php',$content)){
			return $this;
		}

		throw new Exception('失败了');
	}
}